package com.peng.kslc;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * A1TwoSum
 * https://ssg.leetcode-cn.com/problems/add-two-numbers/
 *
 * @author lupeng
 * Created on 2022-07-17
 */
public class A2AddTwoNumbers {

    private static final Logger logger = LoggerFactory.getLogger(A2AddTwoNumbers.class);

    public static void main(String[] args) {

    }

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode sentry = new ListNode(-1);
        ListNode curr = sentry;
        boolean prevCalMoreThenTen = false;
        do {
            int sum = 0;
            if (l1 != null) {
                sum += l1.val;
                l1 = l1.next;
            }
            if (l2 != null) {
                sum += l2.val;
                l2 = l2.next;
            }
            if (prevCalMoreThenTen) {
                sum += 1;
                prevCalMoreThenTen = false;
            }
            if (sum >= 10) {
                prevCalMoreThenTen = true;
                sum = sum % 10;
            }
            curr.next = new ListNode(sum);
            curr = curr.next;
        } while ((l1 != null) || (l2 != null));

        if (prevCalMoreThenTen) {
            curr.next = new ListNode(1);
        }

        return sentry.next;
    }


    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

}
